package com.simpd.activity;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpException;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpResponseException;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.pedant.SweetAlert.SweetAlertDialog;

import com.another.helper.InstallAPK;
import com.another.helper.Logger;
import com.example.simpd.R;
import com.simpd.db_helper.DatabaseHelper;
import com.simpd.http_helper.CustomHttpClient;
import com.simpd.model.AppVersion;
import com.simpd.model.NotifikasiSKPD;
import com.simpd.model.ServerSimpd;
import com.simpd.model.SessionSimpd;
import com.simpd.model.SynchronizeConstant;
import com.simpd.my_list_view.FlatListAdapter;
import com.simpd.my_list_view.RowItem;

public class HomeActivity extends Activity {
	List<RowItem> rowItems; 
	
	ImageButton btnSinkronisasi; 
	RelativeLayout groupKeterangan; 
	RelativeLayout groupLoading;
	TextView textKetTitle; 
	TextView textKetSubtitle;
	ListView list;
	
	ImageButton btnNotifikasi; 
	ImageButton btnPengaturan;
	ImageButton btnTentang; 
	ImageButton btnKeluar; 
	
	
	private static final String SYNCHRONIZE_URL = "/site/synchronize";
	private static final String UPDATE_APP_URL  = "/site/syncApk";
	
	private static final int INDEX_NOTIFIKASI = 0;
	private static final int INDEX_PENGATURAN = 1;
	private static final int INDEX_TENTANG 	  = 2;
	private static final int INDEX_EXIT 	  = 3;
	private String unip;
	private String result; 
	private String errorMessage;
	private int totalUpdateData;
	private ServerSimpd server;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		ActionBar actionBar = getActionBar(); 
		actionBar.hide();
		super.onCreate(savedInstanceState);
		
		DisplayMetrics dm = getResources().getDisplayMetrics();
		
		
		Configuration config = this.getResources().getConfiguration(); 
		if(config.orientation == Configuration.ORIENTATION_LANDSCAPE && 
		   (dm.densityDpi == DisplayMetrics.DENSITY_MEDIUM)){
			setActionLandscape();
		}else{
			setActionPotrait();
		}
		
		
		
		/*list 			= (ListView) findViewById(R.id.home_listview_list);
		groupKeterangan = (RelativeLayout) findViewById(R.id.home_rellayout_keterangan);
		groupLoading	= (RelativeLayout) findViewById(R.id.home_rellayout_loading_group);
		btnSinkronisasi	= (ImageButton) findViewById(R.id.home_button_reload);
		textKetTitle	= (TextView) findViewById(R.id.home_text_keterangan_title); 
		textKetSubtitle = (TextView) findViewById(R.id.home_text_keterangan_subtitle);
		*/
		
		DatabaseHelper db = new DatabaseHelper(this);
		SessionSimpd session = db.getSession();
		if(session == null){
			Intent intent = new Intent(HomeActivity.this, MainActivity.class); 
			startActivity(intent);
			finish();
		}
		
		server = db.getServer(); 
		if(server == null){
			server = new ServerSimpd(); 
			server.setServerUrl(SynchronizeConstant.DEFAULT_SERVER_SIMPD);
			db.insertServer(server);
			Log.d("[insert-server]", "insert server with url : "+server.getServerUrl());
		}
		
		unip = session.getUnip();
		
	}
	
	private void setActionPotrait(){
		setContentView(R.layout.home_activity); 
		btnSinkronisasi = (ImageButton) findViewById(R.id.home_button_reload);
		list 			= (ListView) findViewById(R.id.home_listview_list);
		groupKeterangan = (RelativeLayout) findViewById(R.id.home_rellayout_keterangan);
		groupLoading	= (RelativeLayout) findViewById(R.id.home_rellayout_loading_group);
		textKetTitle	= (TextView) findViewById(R.id.home_text_keterangan_title); 
		textKetSubtitle = (TextView) findViewById(R.id.home_text_keterangan_subtitle);
		
		btnSinkronisasi	= (ImageButton) findViewById(R.id.home_button_reload);
		
		String[] titles = {"Notifikasi", 
				   "Pengaturan", 
				   "Tentang", 
				   "Keluar"};
		int[] icons 	= {R.drawable.icon_notification, 
				   R.drawable.icon_setting,
				   R.drawable.icon_help, 
				   R.drawable.icon_exit};
		
		rowItems 		= new ArrayList<RowItem>();
		RowItem item = null; 
		for (int i = 0; i < titles.length; i++) {
			item = new RowItem(); 
			item.setTitle(titles[i]); 
			item.setIconId(icons[i]); 
			item.setSubtitle("");
			rowItems.add(item);
		}
		
		FlatListAdapter adapter = new FlatListAdapter(this, rowItems);
		list.setVisibility(View.VISIBLE);
		list.setAdapter(adapter);
		
		list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = null;
				switch (position) {
				case INDEX_NOTIFIKASI:
					actionButtonNotifikasi();
					break;
				case INDEX_PENGATURAN: 
					actionButtonPengaturan();
					break;
				case INDEX_TENTANG: 
					actionButtonTentang();				
					break;
				case INDEX_EXIT : 
					actionButtonKeluar();
					break;
				default:
					Toast.makeText(getApplicationContext(), "Belum ada actions", Toast.LENGTH_SHORT).show();
					break;
				}
			}
		});
		
		btnSinkronisasi.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				checkUpdate(v);
			}
		});
		
	}
	
	private void setActionLandscape(){
		setContentView(R.layout.home_activity_tablet); 
		btnSinkronisasi = (ImageButton) findViewById(R.id.home_tablet_button_reload);
		groupKeterangan = (RelativeLayout) findViewById(R.id.home_tablet_rellayout_keterangan);
		groupLoading 	= (RelativeLayout) findViewById(R.id.home_tablet_rellayout_loading_group);
		
		textKetTitle	= (TextView) findViewById(R.id.home_tablet_text_keterangan_title);
		textKetSubtitle = (TextView) findViewById(R.id.home_tablet_text_keterangan_subtitle);
		
		btnNotifikasi	= (ImageButton) findViewById(R.id.home_tablet_btn_notifikasi);
		btnPengaturan	= (ImageButton) findViewById(R.id.home_tablet_btn_pengaturan);
		btnTentang 		= (ImageButton) findViewById(R.id.home_tablet_btn_tentang); 
		btnKeluar		= (ImageButton) findViewById(R.id.home_tablet_btn_keluar); 
		
		btnSinkronisasi.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				checkUpdate(v);
				
			}
		});
		
		btnNotifikasi.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				actionButtonNotifikasi();
			}
		});
		
		btnPengaturan.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				actionButtonPengaturan();
			}
		});
		
		btnTentang.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				actionButtonTentang();
			}
		});
		
		btnKeluar.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				actionButtonKeluar();
			}
		});
		
	}
	
	@Override
	protected void onResume() {
		DatabaseHelper db = new DatabaseHelper(this); 
		server = db.getServer();
		super.onResume();
	}
	
	private void actionButtonNotifikasi(){
		Intent intent = new Intent(HomeActivity.this, NotificationActivity.class);
		intent.putExtra("unip", unip);
		startActivity(intent);
	}
	
	private void actionButtonPengaturan(){
		Intent intent = new Intent(HomeActivity.this, SettingActivity.class);
		startActivity(intent); 
	}
	
	private void actionButtonTentang(){
		PackageManager manager = getPackageManager();
		PackageInfo infoVersion;
		SweetAlertDialog info;
		try {
			 infoVersion = manager.getPackageInfo(getPackageName(), 0);
			 info = new SweetAlertDialog(HomeActivity.this, SweetAlertDialog.CUSTOM_IMAGE_TYPE); 
			 info.setCustomImage(R.drawable.icon_help_blue);
			 info.setTitleText("Tentang Aplikasi"); 
			 info.setContentText("Simpd Mobile Assistant\n" +
			 		"\nVersion Name : "+infoVersion.versionName+
					"\nVersion Code : "+infoVersion.versionCode+"\n\ndeveloped by : " +
					"\nPT. Nusaraya Baskara Jaya @2015" );
			 info.show();
		} catch (NameNotFoundException e) {
			info = new SweetAlertDialog(HomeActivity.this, SweetAlertDialog.ERROR_TYPE);
			info.setTitleText("Oops..!!"); 
			info.setContentText(e.toString());
			info.show();
			e.printStackTrace();
			
		}
	}
	
	private void actionButtonKeluar(){
		SweetAlertDialog alert = new SweetAlertDialog(HomeActivity.this, 
				SweetAlertDialog.WARNING_TYPE);
		alert.setTitleText("Apakah Anda Yakin ?"); 
		alert.setContentText("Jika Anda log out, maka semua data dan session akan terhapus !!");
		alert.setConfirmText("Ya, Keluar"); 
		alert.setCancelText("Batal"); 
		alert.showCancelButton(true); 
		alert.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
			
			@Override
			public void onClick(SweetAlertDialog sweetAlertDialog) {
				sweetAlertDialog.cancel();
			}
		});
		
		alert.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
			
			@Override
			public void onClick(SweetAlertDialog sweetAlertDialog) {
				DatabaseHelper db = new DatabaseHelper(HomeActivity.this); 
				db.deleteAllNotifikasi();
				SessionSimpd session = db.getSession();
				db.resetSession(session);
				sweetAlertDialog.dismiss();
				Intent intent = new Intent(HomeActivity.this, MainActivity.class); 
				startActivity(intent);
				finish(); 
			}
		});
		alert.show();
	}
	
	private void checkUpdate(View v){
		// 1. request server to get lastest apk file
		// 2. compare apps version with server apk file
		// 3. if server apk version higher than its app's version, then update apk
		// 4. if false, update data sinkronize
		
		String url = server.getServerUrl()+UPDATE_APP_URL;
		Thread thread = new Thread(new CheckUpdateThread(url));
		thread.start();
		
	}
	
	private void updateApk(final String url){
		Intent intent; 
		PackageManager manager = getPackageManager(); 
		try {
			intent = manager.getLaunchIntentForPackage("com.nusaraya.simpd"); 
			if(intent == null){
				throw new PackageManager.NameNotFoundException(); 
			}
			intent.addCategory(Intent.CATEGORY_LAUNCHER); 
			startActivity(intent); 
		} catch (PackageManager.NameNotFoundException e) {
			HomeActivity.this.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					SweetAlertDialog dialog = new SweetAlertDialog(HomeActivity.this, SweetAlertDialog.PROGRESS_TYPE);
					dialog.setTitleText("updating apps...");
					dialog.setCancelable(false);
					
					SweetAlertDialog errorDialog = new SweetAlertDialog(HomeActivity.this, SweetAlertDialog.ERROR_TYPE); 
					InstallAPK downloadAndInstall = new InstallAPK(HomeActivity.this, dialog); 
					downloadAndInstall.setErrorDialog(errorDialog);
					downloadAndInstall.execute(url);
					
					groupLoading.setVisibility(View.GONE);
					textKetTitle.setText("Update App available");
					textKetSubtitle.setText("install applikasi terbaru");
					groupKeterangan.setVisibility(View.VISIBLE)
					;
				}
			});
		}
	}
	
	private void processSinkronisasi(View v){
		DatabaseHelper db 	= new DatabaseHelper(getApplicationContext());
		server = db.getServer();
		String url = server.getServerUrl()+SYNCHRONIZE_URL;
		
		NotifikasiSKPD notifikasi = db.getLastNotifikasi(); 
		String lastUpdated = "";
		if(notifikasi !=null){
			lastUpdated = notifikasi.getTanggalUpdate(); 
		}
		
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); 
		postParameters.add(new BasicNameValuePair("unip", unip)); 
		postParameters.add(new BasicNameValuePair("fulltok", "123")); 
		postParameters.add(new BasicNameValuePair("last_updated", lastUpdated));
		
		Thread thread = new Thread(new SinkronisasiThread(url, postParameters));
		thread.start();
	}
	
	/**
	 * 
	 * @param url
	 * @param postParameters
	 * @return true if success, false otherwise
	 */
	private boolean sinkronisasiUseThreads(String url, ArrayList<NameValuePair> postParameters){
		boolean successful = false;
		
		String response = null;
		result 	= null;
		
		Log.d("[url]", "url : "+url);
		Log.d("[post-params]", "unip : "+postParameters.get(0).getValue()+"" +
							   "fulltok : "+postParameters.get(1).getValue()+"" +
							   "last_updated : "+postParameters.get(2).getValue());
		
		try {
			response = CustomHttpClient.executeHttpPost(url, postParameters);
			Log.d("[post-request]", "perform post request");
			
			result = response.toString();
			
			
//			result = result.replaceAll("\\s+", "");
			Log.d("[request-result]", "result : "+result);
			JSONArray jArray = new JSONArray(result);			
			DatabaseHelper db = new DatabaseHelper(this);
			NotifikasiSKPD notifikasi;
			long inserted_id = 0;
			totalUpdateData  = 0;
			String tempUrl 	 = null;
			errorMessage = "";
			for (int i = 0; i < jArray.length(); i++) {
				JSONObject jsonData = jArray.getJSONObject(i);
				notifikasi = new NotifikasiSKPD();
				notifikasi.setSkpd(jsonData.getString("skpd").toString());
				notifikasi.setTanggalUpdate(jsonData.getString("tanggal_berubah_status").toString()); 
				notifikasi.setPerihal(jsonData.getString("perihal").toString()); 
				notifikasi.setTipeSurat(jsonData.getString("tipe_surat").toString());
				notifikasi.setSebagai(jsonData.getString("sebagai").toString());
				tempUrl = jsonData.getString("url").toString();
				Log.d("[url-from json]", "url : "+tempUrl);
				tempUrl = tempUrl.replaceAll("\\\\", "");
				Log.d("[inserted-url]", "url : "+tempUrl);
				notifikasi.setOnlineUrl(tempUrl);
				notifikasi.setKeterangan(DatabaseHelper.DEFAULT_KETERANGAN);
				
				inserted_id = db.insertNotifikasi(notifikasi);
				if(inserted_id !=0){
					Log.d("[inserting-data]", "insert skpd "+notifikasi.getSkpd()+" successfully!");
				}else{
					Log.e("[inserting-failed]", "insert skpd : "+notifikasi.getSkpd()+" failed!!");
				}
				inserted_id = 0;
				
			}
			totalUpdateData = jArray.length();
		} catch (HttpResponseException e) {
			Log.e("[error-httpResponse]", e.getMessage());
			errorMessage = "respond dari server tidak sesuai format yang ditentukan!!";
			e.printStackTrace();
			Logger.e(HomeActivity.this, "Synchronize error", "Server response : \n"+
										result+"\nException message : "+e.toString());
		} catch (HttpException e) {
			Log.e("[error-http]", ""+e.getMessage());
			errorMessage = "terdapat kesalahan ketika mengakses server!!";
			e.printStackTrace();
			Logger.e(HomeActivity.this, "Synchronize error", e.toString());
		} catch (HttpHostConnectException e) {
			Log.e("[error-http-connection]", ""+e.getMessage());
			errorMessage = "tidak bisa terhubung dengan server! Silahkan periksa koneksi internet Anda dan coba beberapa saat lagi!!";
			e.printStackTrace();
			Logger.e(HomeActivity.this, "Synchronize error", e.toString());
		}catch (UnknownHostException e) {
			Log.e("[error-http-connection]", ""+e.getMessage());
			errorMessage = "tidak bisa terhubung dengan server! Silahkan periksa koneksi internet Anda dan coba beberapa saat lagi!!";
			e.printStackTrace();
			Logger.e(HomeActivity.this, "Synchronize error", e.toString());
		}
		
		catch (Exception e) {
			Log.e("[error-exception]", ""+e.getMessage());
			errorMessage = "tidak bisa terhubung dengan server! Silahkan periksa koneksi internet Anda!";
			e.printStackTrace();
			Logger.e(HomeActivity.this, "Syncronize error", e.toString());
		}finally{
			HomeActivity.this.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					if(result !=null && errorMessage == ""){
						SweetAlertDialog alert = new SweetAlertDialog(HomeActivity.this, 
																	  SweetAlertDialog.SUCCESS_TYPE);
						
						alert.setTitleText("Update data berhasil !");
						String message = "";
						if(totalUpdateData > 0){
							message = totalUpdateData+" data baru berhasil ditambahkan!";
						}else{
							message = "Belum terdapat data baru!";
						}
						
						alert.setContentText(message);
						alert.show();
						
					}else{
						SweetAlertDialog alert = new SweetAlertDialog(HomeActivity.this, 
													SweetAlertDialog.ERROR_TYPE);
						alert.setTitleText("Sinkronisasi gagal!");
						alert.setContentText("Terjadi kesalahan karena : "+errorMessage);
						alert.show();
					}
					groupLoading.setVisibility(View.GONE);
					textKetTitle.setText(getString(R.string.tekan_tombol_sinkronisasi)); 
					textKetSubtitle.setText(getString(R.string.update_notifikasi_terbaru));
					groupKeterangan.setVisibility(View.VISIBLE);
				}
			});
		}
		
		 
		return successful;
	}
	
	private void checkUpdateUsingThread(String url){
		String respond = null;
		result = null; 
		Log.d("[check update]", "url update : "+url);
		AppVersion appVersion = null;
		try {
			respond = CustomHttpClient.executeHttpGet(url);
			result = respond.toString(); 
			Log.d("update result", "result : "+result);
			if(result!=null){
				
				JSONObject jsonObject = new JSONObject(result);
				appVersion = new AppVersion();
				appVersion.setVersionCode((int) jsonObject.getInt("version_code")); 
				appVersion.setVersionName((String) jsonObject.getString("version_name"));
				appVersion.setDownloadUrl((String) jsonObject.getString("file"));
				appVersion.setReleaseUpdate((String) jsonObject.getString("created_at"));
				Log.d("[lastest app]", appVersion.toString());
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(appVersion !=null){
				PackageManager manager = getPackageManager(); 
				try {
					PackageInfo infoPackage = manager.getPackageInfo(getPackageName(), 0);
					if(appVersion.getVersionCode() > infoPackage.versionCode){
						//update apk
						updateApk(server.getServerUrl()+appVersion.getDowloadUrl());
					}else{
						processSinkronisasi(new View(HomeActivity.this));
					}
				} catch (NameNotFoundException e) {
					e.printStackTrace();
				}
			}else{
				processSinkronisasi(new View(HomeActivity.this));
			}
		}
	}
	
	
	/**
	 * 
	 * InnerClass SinkronisasiThread 
	 * digunakan untuk menjalankan sinkronisasi 
	 * di Thread yang terpisah dari UIMainThread
	 * 
	 */
	
	
	private class SinkronisasiThread implements Runnable{
		private ArrayList<NameValuePair> postParameters; 
		private String url;
		
		/**
		 * @param url : alamat url untuk melakukan process httpClient
		 * @param postParameters : parameter untuk httpPost
		 */
		public SinkronisasiThread(String url, ArrayList<NameValuePair> postParameters){
			this.url 			= url;
			this.postParameters = postParameters;
		}
		
		@Override
		public void run() {
			sinkronisasiUseThreads(url, postParameters);			
			/*HomeActivity.this.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					groupKeterangan.setVisibility(View.GONE);
					groupLoading.setVisibility(View.VISIBLE);
				}
			});*/
		}
		
	}
	
	private class CheckUpdateThread implements Runnable{
		private String url;
		public CheckUpdateThread(String url) {
			this.url = url;
		}
		@Override
		public void run() {
			HomeActivity.this.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					groupKeterangan.setVisibility(View.GONE);
					groupLoading.setVisibility(View.VISIBLE);
				}
			});
			checkUpdateUsingThread(this.url);
		}
		
	}
	
	
}
